<?php


namespace Soen\Esign;


use GuzzleHttp\Client;
use Soen\Esign\Exception\EsignException;
use Soen\Esign\Exception\EviException;

class Http
{
    const urlArr = [
        //定义所属行业类型
        'busAdd' => '/evi-service/evidence/v1/sp/temp/bus/add',
        //定义业务凭证（名称）
        'sceneAdd' => '/evi-service/evidence/v1/sp/temp/scene/add',
        //定义业务凭证中某一证据点名称
        'segAdd' => '/evi-service/evidence/v1/sp/temp/seg/add',
        //定义业务凭证中某一证据点的字段属性
        'segPropAdd' => '/evi-service/evidence/v1/sp/temp/seg-prop/add',
        //创建原文存证证据点
        'segmentOriginalAdv' => '/evi-service/evidence/v1/sp/segment/original-adv/url',
        //创建证据链
        'createEviChain' => '/evi-service/evidence/v1/sp/scene/voucher',
        //追加据点
        'appendEviPoint'    =>  '/evi-service/evidence/v1/sp/scene/append',
        //查询区块链上链信息
        'getChainInfo' => '/evi-service/evidence/v1/blockchain/antPushInfo',
    ];
    protected $httpClient;
    public $config;

    public function __construct(Config $config)
    {
        $this->config = $config;
        $this->httpClient = new Client([
            'base_uri' => $this->getEviHost(),
            'timeout' => 10,
            'verify' => false
        ]);
    }

    /**
     * 接口host
     * @return mixed
     */
    public function getEviHost()
    {
        return $this->config->getEviApiHost();
    }

    /**
     * 获取最终完整请求接口地址
     * @param $uri
     * @return string
     */
    public function getUrl($uri)
    {
        if (empty(self::urlArr[$uri])) {
            throw new EsignException('未找到请求的接口地址');
        }
        return $this->getEviHost() . self::urlArr[$uri];
    }

    /**
     * 获取签名
     * @param $param
     * @return string
     */
    public function getSignature($param)
    {
        $signature = hash_hmac('sha256', json_encode($param), $this->config->getEviAppSecret(), false);
        return $signature;
    }

    /**
     * post 请求
     * @param $uri
     * @param $param
     * @return mixed
     */
    public function post($uri, $param)
    {
        $data = $this->httpClient->post($this->getUrl($uri), [
            'json' => $param,
            'headers' => [
                'X-timevale-project-id' => $this->config->getEviAppId(),
                'X-timevale-signature' => $this->getSignature($param),
                'X-timevale-signature-algorithm' => 'hmac-sha256',
                'X-timevale-mode' => 'package'
            ]
        ]);
        $content = json_decode($data->getBody()->getContents(), 1);
        if ($content['errCode']) {
            throw new EviException($content['msg']);
        }
        return $content;
    }
}